<template>
	<div class="search">
		<div class="header">
			<van-search v-model.trim="keyword" show-action placeholder="请输入搜索关键词" @search="onSearch">
				<template #left>
					<van-icon name="arrow-left" class="arrow-left" @click="$router.back()" />
				</template>
				<template #action>
					<div @click="onSearch">搜索</div>
				</template>
			</van-search>
		</div>

		<div class="group" v-show="!searchlist.length">
			<h3 class="title">历史记录</h3>
			<div class="list">
				<span class="item" v-for="(item, index) in historylist" :key="index" @click="(keyword = item), onSearch()">{{ item }}</span>
				<p v-show="!historylist.length">没有历史记录...</p>
			</div>
			<div v-show="historylist.length" class="remove" @click="removefn">清空历史记录</div>
		</div>

		<div class="searchR" v-show="searchlist.length">
			<h3 class="title">搜索结果</h3>
			<router-link class="searchlist" v-for="item in searchlist" :key="item.id" :to="'/articleDetail/?articleId=' + item.id">{{ item.title }}<van-icon name="arrow" class="arrow"/></router-link>
		</div>
	</div>
</template>

<script>
import {sethistory, gethistory, removehistory} from "@/utils/localData";
import {getPostSearchAPI} from "@/apis/News";
export default {
	data() {
		return {
			keyword: "",
			searchlist: [],
			historylist: gethistory() || [],
		};
	},
	methods: {
		async onSearch() {
			if (this.keyword === "") return this.$toast("请输入搜索关键词");

			const res = await getPostSearchAPI({
				keyword: this.keyword,
			});
			console.log(res.data.data);
			this.searchlist = res.data.data;
			this.historylist.unshift(this.keyword);
			this.historylist = [...new Set(this.historylist)];
			// this.historylist.length = 15 //控制搜索记录的条数 会影响原数组
			this.historylist = this.historylist.slice(0, 10);
			if (res.data.data.length === 0) {
				this.keyword = "";
				this.$toast("没有搜索到相关内容");
			}
		},
		removefn() {
			this.$dialog
				.confirm({
					title: "是否清空",
				})
				.then(() => {
					// on confirm
					removehistory();
					this.historylist = [];
				})
				.catch(() => {
					// on cancel
				});
		},
	},
	watch: {
		keyword() {
			if (this.keyword === "") return (this.searchlist = []);
		},
		historylist() {
			sethistory(this.historylist);
		},
	},
};
</script>

<style lang="less" scoped>
.arrow-left {
	width: 30px;
	font-size: 20px;
}
.title {
	font-style: 20px;
	font-weight: 600;
	margin-bottom: 6px;
}
.group {
	padding: 10px;
	.list {
		display: flex;
		flex-wrap: wrap;
		.item {
			font-size: 14px;
			padding: 5px;
			border: 1px solid #ccc;
			margin-right: 10px;
			margin-bottom: 6px;
		}
	}
	.remove {
		padding-top: 10px;
		text-align: center;
		cursor: pointer;
	}
}
.searchR {
	padding: 10px;
	.searchlist {
		display: block;
		position: relative;
		padding: 5px;
		padding-right: 10px;
		border-bottom: 1px solid #666;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		margin-bottom: 10px;
		.arrow {
			position: absolute;
			right: 0;
			top: 8px;
		}
	}
}
</style>
